const path = require('path')
const HtmlWebpackInlineSourcePlugin = require('html-webpack-inline-source-plugin')
const { publicPath, title } = require('./src/settings')
function resolve(dir) {
  return path.join(__dirname, dir)
}

const mockServer = () => {
  if (process.env.NODE_ENV === 'development') {
    return require('./mock/mockServer.js')
  } else {
    return ''
  }
}

// cdn use fixed version
const cdn = {
  preconnect: [
    // link preconnect
    'https://unpkg.com',
    'https://cdn.bootcdn.net'
  ],
  css: [
    // element-ui css
    // 'https://unpkg.com/element-ui@1.0.2-beta.36/lib/theme-chalk/index.css'
  ],
  js: [
    // npm list --depth=0 check version
    // vue must at first!
    'https://unpkg.com/vue@3.0.11/dist/vue.runtime.global.prod.js',
    'https://unpkg.com/vue-router@4.0.5/dist/vue-router.global.prod.js',
    'https://unpkg.com/vuex@4.0.0/dist/vuex.global.prod.js',
    //
    'https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js'
    // element-ui js
    // 'https://unpkg.com/element-plus@1.0.2-beta.36/lib/index.full.js'
  ]
}

module.exports = {
  publicPath,
  // outputDir: path.resolve('../src/main/webapp/weizhan/entrance', `./${dir}`),
  productionSourceMap: false,
  lintOnSave: 'warning',
  devServer: {
    disableHostCheck: true,
    // proxy: {
    //   '/child': {
    //     // target host 会将请求代理到此
    //     target: 'https://betainfo.net',
    //     // needed for virtual hosted sites
    //     changeOrigin: true,
    //     // proxy websockets
    //     ws: true
    //   },
    //   // [baseURL]: {
    //   //   target: `http://你的后端接口地址`,
    //   //   ws: true,
    //   //   changeOrigin: true,
    //   //   pathRewrite: {
    //   //     ["^/" + baseURL]: "",
    //   //   },
    //   // },
    // },
    after: mockServer()
  },
  // This is preferred over manually tapping into specific loaders using chainWebpack, because these options need to be applied in multiple locations where the corresponding loader is used.
  css: {
    loaderOptions: {
      // 给 sass-loader 传递选项
      sass: {
        // @/ 是 src/ 的别名
        // 所以这里假设你有 `src/variables.scss` 这个文件
        prependData: `@import "@/assets/scss/_variables.scss";
        @import "@/assets/scss/_mixin.scss";`
        // additionalData: `@import "~@/assets/scss/_variables.scss";
        // @import "~@/assets/scss/_mixin.scss";`
      }
    }
  },
  chainWebpack: (config) => {
    // it can improve the speed of the first screen, it is recommended to turn on preload
    // it can improve the speed of the first screen, it is recommended to turn on preload
    config.plugin('preload').tap(() => [
      {
        rel: 'preload',
        // to ignore runtime.js
        // https://github.com/vuejs/vue-cli/blob/dev/packages/@vue/cli-service/lib/config/app.js#L171
        fileBlacklist: [/\.map$/, /hot-update\.js$/, /runtime\..*\.js$/, /runtime~.+\.js$/],
        include: 'initial'
      }
    ])

    // when there are many pages, it will cause too many meaningless requests
    config.plugins.delete('prefetch')

    // set svg-sprite-loader
    config.module.rule('svg').exclude.add(resolve('src/icons')).end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()

    if (process.env.NODE_ENV === 'production') {
      // mutate config for production...
      // config.devtool('none')

      // production下使用cdn
      config.externals({
        vue: 'Vue', // 24.2kb
        'vue-router': 'VueRouter', // 10.2kb
        vuex: 'Vuex', // 4.6kb
        axios: 'axios' // 5.5kb
      })

      config.optimization
        .runtimeChunk({
          name: 'runtime~manifest'
        })
        .splitChunks({
          chunks: 'all',
          cacheGroups: {
            vendors: {
              name: 'chunk-vendors',
              test: /[\\/]node_modules[\\/]/,
              priority: -10,
              chunks: 'initial' // only package third parties that are initially dependent
            },
            elementPlus: {
              name: 'chunk-elementUI', // split elementUI into a single package
              priority: -15, // the weight needs to be larger than libs and app or it will be packaged into libs or app
              test: /[\\/]node_modules[\\/]_?element-plus(.*)/ // in order to adapt to cnpm
            },
            common: {
              name: 'chunk-common',
              minChunks: 2, //  minimum common number
              priority: -20,
              // all
              chunks: 'all',
              reuseExistingChunk: true
              // minSize: 30000
            }
          }
        })

      config.plugin('inlineManifest').after('html').use(HtmlWebpackInlineSourcePlugin)

      config.plugin('html').tap((args) => {
        args[0].title = title
        args[0].filename = 'index.html'
        args[0].productLog = true
        args[0].chunksSortMode = 'dependency'

        // Inline all files which names start with “runtime~” and end with “.js”.
        // That’s the default naming of runtime chunks
        /* see https://developers.google.com/web/fundamentals/performance/webpack/use-long-term-caching Inline webpack runtime to save an extra HTTP request */
        args[0].inlineSource = 'runtime~.+\\.js'

        // use cdn
        args[0].cdn = cdn
        return args
      })
    } else {
      // mutate for development...
    }
  }
}
